package com.llcbenwu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;

/**
 * 将令牌存放到redis中
 * @author lilinchun
 * @date 2021/11/17 0017 17:57
 */
@Configuration
public class TokenRedisJwtConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;




    /**
     * 拿到redis的连接工厂就会将数据存放到redis中
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "llc.security.oauth2",name = "storeType", havingValue = "redis")
    public TokenStore redisTokenStore(){
        return  new RedisTokenStore(redisConnectionFactory);
    }


    @Configuration
    @ConditionalOnProperty(prefix = "llc.security.oauth2",name = "storeType", havingValue = "jwt",matchIfMissing = true)
    public static class JwtTokenConfig{



        @Bean
        public  TokenStore jwtTokenStroe(){
            return new JwtTokenStore(jwtAccessTokenConverter());
        }


        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter(){
            JwtAccessTokenConverter accessTokenConverter=new JwtAccessTokenConverter();
            accessTokenConverter.setSigningKey(SecurityProperies.JWT_SECURITY); //设置jwt秘钥 （非常重要如果谁知道你的秘钥就可以随意进入系统）
            return accessTokenConverter;
        }

        @Bean
//        @ConditionalOnMissingBean(name = "jwtTokenEnhancer")  //只要有方法实现了jwtTokenEnhancer下面配置就能被覆盖
        @ConditionalOnBean(TokenEnhancer.class)
        public TokenEnhancer jwtTokenEnhancer(){
                return  new LlcJwtTokenEnhancer();
        }
    }


}
